<?php

namespace app\admin\controller;

use think\Controller;
use think\Request;
use app\admin\model\Chapter;
use app\admin\model\Course;

class Chapters extends Controller
{
//    public function __construct(Request $request)
//    {
//        parent::__construct();
//        $course_id = $request->param('course_id');
//        $course = Course::where('id', $course_id)->find();
//        $this->assign('course', $course);
//    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $course_id = $request->param('course_id');
        $course = Course::where('id', $course_id)->find();
        $chapters = Chapter::where('course_id', $course_id)->paginate(10);
//        dump($chapters);

        return view('Chapters/index', compact('chapters', 'course'));
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create(Request $request)
    {
        $id = $request->param('id');
        $course = Course::find($id);
//        dump($course);


        return view('Chapters/create', compact('course'));
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
//        dump($request->param());exit;
        $id = $request->param('course_id');
        $data = $request->param();
        Chapter::create($data);
        return redirect("/admin/Chapters/index/course_id/$id");
    }

    /**
     * 显示指定的资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $chapter = Chapter::find($id);
        return view('Chapters/edit', compact('chapter'));
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $chapter = Chapter::find($id);
//        dump($chapter);exit;
        $id = $chapter->course_id;
        $chapter->allowField(true)->save($request->param(), ['id' => $id]);
        return redirect("/admin/Chapters/index/course_id/$id");


    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete($id)
    {


        $chapter = Chapter::find($id);
        $ids = $chapter->course_id;
        $chapter->delete($id);

        return redirect("/admin/Chapters/index/course_id/$ids");

    }
}
